<?php

/**
 * 系统登录
 */

namespace app\member\api;

use \app\base\api\BaseApi;

class LoginApi extends BaseApi {

    /**
     * 用户登录
     */
    public function index() {
        $data = target('Member/Member', 'service')->loginUser($this->data['username'], $this->data['password']);
        if(!$data) {
            $this->error(target('Member/Member', 'service')->getError());
        }
        $this->success('帐号登录成功!', $data);
    }

    /**
     * 第三方登录
     */
    public function bind() {
        $openId = $this->data['open_id'];
        $type = $this->data['type'];
        if (empty($openId) || empty($type)) {
            $this->error('oath参数错误!');
        }
        $loginInfo = target('member/MemberConnect')->getWhereInfo([
            'open_id' => $openId,
            'type' => $type
        ]);
        if (empty($loginInfo)) {
            $this->error('第三方登录信息不存在!');
        }
        if ($loginInfo['user_id']) {
            $this->error('已绑定会员账号');
        }

        $oathData = unserialize($loginInfo['data']);

        $model = target('member/MemberUser');
        $model->beginTransaction();
        $userName = $this->data['username'];
        $password = $this->data['password'];
        $code = $this->data['code'];
        if (empty($userName) || empty($password)) {
            $this->error('用户名或密码未填写！');
        }

        $userInfo = target('member/Member', 'service')->isUser($userName);

        if ($userInfo) {
            $status = target('member/Member', 'service')->checkVerify($userName, $code);
            if (!$status) {
                return $status;
            }
            $loginData = target('member/Member', 'service')->loginUser($userName, $password);
            if (!$loginData) {
                $model->rollBack();
                $this->error(target('member/Member', 'service')->getError());
            }
            $userInfo = $loginData['data'];
            if (!empty($userInfo['avatar'])) {
                $oathData['avatar'] = '';
            }
            if (!empty($userInfo['nickname'])) {
                $oathData['nickname'] = '';
            }
        } else {
            $loginData = target('member/Member', 'service')->regUser($userName, $password, $code, $oathData['nickname']);
            if (!$loginData) {
                $this->error(target('member/Member', 'service')->getError());
            }
        }

        if (!target('member/Member', 'service')->connectUser($loginInfo['connect_id'], $loginData['uid'], $oathData['nickname'], $oathData['avatar'])) {
            $model->rollBack();
            $this->error(target('member/Member', 'service')->getError());
        }
        $model->commit();
        $this->success('登录成功！', $loginData);

    }

}